#!/user/bin/python
# -*- coding: utf-8 -*-
'''
 @Time    : 2018/5/6 15:48
 @File    : persistent.py
 @desc    :
'''
from commonSpiders.global_context_manager.context_manager import ContextManager
from commonSpiders.net.extend_context import ContextExtend
from commonSpiders.net.message.socketio_msg import Failure, MsgStatus, Success
from commonSpiders.scrapy_clusters_manager.config.constant import ManagerConstant
from commonSpiders.scrapy_clusters_manager.entity.context_entity import SocketIoContext
from commonSpiders.scrapy_clusters_manager.mysql.persistent import MysqlPerisistence
from commonSpiders.storage.redis.redis_client import RedisClient
from commonSpiders.utils.singleton import singleton


@singleton
@ContextExtend.extend('CrawlerManagerService', priority=1, async=False)
class CrawlerManagerService(object):

    '''
    爬虫管理器服务，用于对爬虫管理器进行管理的服务
    '''

    SYSTEM_KEY = 'SYSTEM_%S'

    def __init__(self):
        self.context = ContextManager()
        self.redis = RedisClient()
        self.mysql_service = MysqlPerisistence()

    def register_crawler_manager(self, data, socketio):
        '''
        注册爬虫管理器
        :param crawler_process_info:
        :return:
        '''
        if not data:
            return Failure('没有管理器信息')
        if not MsgStatus.is_success(data['status']):
            return Failure('没有管理器信息')
        mac = data['mac']
        manager_guid = data['manager_guid']
        self.context.setdefault(ManagerConstant.CRAWLER_MANAGER_KEY, SocketIoContext())
        self.context.get_context(ManagerConstant.CRAWLER_MANAGER_KEY).set_socketio(mac, manager_guid, socketio)
        return Success('注册成功')

    def logout_crawler_manager(self, guid):
        pass

    def update_manager_system_cup(self, data):
        mac = data['mac']
        cpu = data['cpu']
        self.redis.hset(self.SYSTEM_KEY % mac, 'cpu', cpu)

    def update_manager_system_meu(self, data):
        mac = data['mac']
        meu = data['meu']
        self.redis.hset(self.SYSTEM_KEY % mac, 'meu', meu)

    def update_manager_system_hd(self, data):
        mac = data['mac']
        hd = data['hd']
        self.redis.hset(self.SYSTEM_KEY % mac, 'hd', hd)

    def update_manager_system_net(self, data):
        mac = data['mac']
        net = data['net']
        self.redis.hset(self.SYSTEM_KEY % mac, 'net', net)
